#pragma once
#include <iostream>
#include<vector>
#include<semaphore.h>//POSIX头文件
#include<pthread.h>
using namespace std;
const static int defaultcap=5;

template<class T>
class RingQueue
{
private://对信号量的pv操作和互斥量加锁解锁进行封装
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void UnLock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }
public:
    RingQueue(int cap=defaultcap)
    :cap_(cap),ringqueue_(cap),c_step(0),p_step(0)
    {
        pthread_mutex_init(&c_mutex,nullptr);
        pthread_mutex_init(&p_mutex,nullptr);
        sem_init(&cdata_sem,0,0);//空间中数据资源初始化为0
        sem_init(&pspace_sem,0,cap);//空间资源初始化为满
    }

    void push(const T& in)//生产者生产
    {//这里先申请信号量在加锁可以提高效率，申请到信号量在去申请锁，当解锁后就可以直接
    //申请锁不用再等待申请信号量，若信号量申请完了直接去休眠等待唤醒
        P(pspace_sem);
        Lock(p_mutex);
        ringqueue_[p_step++]=in;
        p_step%=cap_;//保证数据一直在环形队列中；
        UnLock(p_mutex);
        V(cdata_sem);
    }

    void Pop(T*out)
    {
        P(cdata_sem);
        Lock(c_mutex);
        *out=ringqueue_[c_step++];
        c_step%=cap_;
        UnLock(c_mutex);
        V(pspace_sem);
    }
    ~RingQueue()
    {
        pthread_mutex_destroy(&c_mutex);
        pthread_mutex_destroy(&p_mutex);
        sem_destroy(&cdata_sem);
        sem_destroy(&pspace_sem);
    }
private:
    vector<T> ringqueue_;//后面加_都代表为类内元素
    int cap_;
    int c_step;//消费者下标
    int p_step;//生产者下标
    sem_t cdata_sem;//消费者关注的数据资源
    sem_t pspace_sem;//生产者关注的空间资源
    pthread_mutex_t c_mutex;
    pthread_mutex_t p_mutex;
};